<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.member_delivery_bind_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="danger"
                   size="small"
                   plain
                   v-if="permission.member_delivery_bind_sync"
                   @click="handleSync">同 步
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="memberIds">
        <el-tag :key="index" v-for="(item, index) in row.memberList" style="margin-right: 10px">姓名：{{ item.name }}，电话：{{ item.phone }}；</el-tag>
      </template>
      <template slot-scope="{type, disabled}" slot="memberIdsForm">
        <el-button type="primary" @click="handleAddMember">添加成员</el-button>
        <div style="margin-top: 20px">
          <el-tag :key="index" style="margin-right: 10px; margin-top: 10px" v-for="(item, index) in memberSelectionList" closable @close="handleRemove(index)">
            姓名：{{ item.name }}，电话：{{ item.phone }}
          </el-tag>
        </div>
      </template>
      <template slot-scope="{type, disabled}" slot="addressIdForm">
        <el-autocomplete v-model="addressName" style="width: 100%" :fetch-suggestions="queryAddressAsync"
                         placeholder="搜索公共地址" @select="handleAddressSelect" clearable></el-autocomplete>
      </template>
      <template slot-scope="{row}"
                slot="addressId">
        <el-tag v-if="row.openAddress && row.openAddress.addressText && row.openAddress.addressText !== ''" type="primary">
          {{ `【${row.openAddress.merchantName}】${row.openAddress.addressText} -${row.openAddress.otherInfo}` }}
        </el-tag>
        <el-tag v-else-if="row.openAddress && row.openAddress.isTakeSelf && row.openAddress.isTakeSelf === 1" type="primary">
          {{ `【${row.openAddress.merchantName}】 自取` }}
        </el-tag>
        <el-tag v-else type="info">未设置</el-tag>
      </template>
    </avue-crud>
    <el-drawer
      title="可选会员"
      :visible.sync="addMemberVisible"
      append-to-body
      :before-close="handleAddMemberClose"
      size="800px"
    >
      <basic-container>
        <avue-crud :option="memberOption"
                   :table-loading="loading"
                   :data="memberData"
                   :page="memberPage"
                   ref="memberCrud"
                   @search-change="memberSearchChange"
                   @search-reset="memberSearchReset"
                   @current-change="memberCurrentChange"
                   @size-change="memberSizeChange"
                   @on-load="memberOnLoad">
          <template slot="menuLeft">
            <el-input placeholder="搜索姓名" v-model="searchName" clearable @change="searchNameChange"></el-input>
          </template>
          <template slot="menu" slot-scope="{row}">
            <el-button size="small"
                       type="text"
                       @click="handleSelect(row)">选择
            </el-button>
          </template>
        </avue-crud>
        <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddMemberClose">取 消</el-button>
      </span>
      </basic-container>
    </el-drawer>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, memberList as getMemberList, sync} from "@/api/delivery/member_delivery_bind";
  import {getListByMemberIds} from "@/api/address/open_address";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        searchName: '',
        addMemberVisible: false,
        memberSelectionList: [],
        memberOption: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          menuWidth: 100,
          tip: false,
          border: true,
          index: true,
          viewBtn: false,
          addBtn: false,
          refreshBtn: false,
          editBtn: false,
          delBtn: false,
          selection: false,
          column: [
            {
              label: "昵称",
              prop: "nickname",
              rules: [{
                required: true,
                message: "请输入昵称",
                trigger: "blur"
              }]
            },
            {
              label: "姓名",
              prop: "name",
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }]
            },
            {
              label: "头像",
              prop: "avatar",
              dataType: 'string',
              type: 'upload',
              span: 24,
              listType: 'picture-card',
              propsHttp: {
                res: 'data',
                url: 'link',
                name: 'originalName'
              },
              limit: 1,
              action: '/api/blade-resource/oss/endpoint/put-file'
            },
            {
              label: "手机",
              prop: "phone",
              rules: [{
                required: true,
                message: "请输入手机",
                trigger: "blur"
              }]
            },
            {
              label: "注册时间",
              prop: "createTime"
            },
          ]
        },
        memberData: [],
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        memberPage: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "成员",
              prop: "memberIds",
              slot: true,
              row: true,
              rules: [{
                required: true,
                message: "请选择成员",
                trigger: "blur"
              }],
              span: 18,
              overHidden: true,
              formslot: true,
            },
            {
              label: "邀请码",
              prop: "code",
              width: 80,
              display: false
            },
            {
              label: "配送地址",
              prop: "addressId",
              slot: true,
              row: true,
              span: 18,
              width: 300,
              overHidden: true,
              formslot: true,
              rules: [{
                required: true,
                message: "请选择配送地址",
                trigger: "blur"
              }]
            },
            {
              label: "联系人",
              prop: "receiverName",
              display: false
            },
            {
              label: "联系电话",
              prop: "telephone",
              display: false
            },
            {
              label: "备注",
              prop: "remark",
              overHidden: true,
              type: 'textarea',
              span: 18,
            },
          ]
        },
        data: [],
        addressList: [],
        addressName: '',
      };
    },
    watch: {
      memberSelectionList: function(val) {
        this.form.memberIds = val.map(e => e.id).join(',')
      },
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.member_delivery_bind_add, false),
          viewBtn: false,
          delBtn: this.vaildData(this.permission.member_delivery_bind_delete, false),
          editBtn: this.vaildData(this.permission.member_delivery_bind_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleSelect(row) {
        const memberIds = this.memberSelectionList.map(item => item.id)
        if (memberIds.includes(row.id)) {
          this.$message.warning('该用户已添加, 请勿重复添加！')
          return
        }
        this.memberSelectionList.push(row)
        this.handleGetAddressList()
        this.handleAddMemberClose()
      },
      handleAddressSelect(val) {
        this.$set(this.form, 'addressId', val.id)
      },
      queryAddressAsync(queryString, cb) {
        const restaurants = this.addressList.map(item => {
          if (item.isTakeSelf === 1) {
            item.value = `【${item.merchantName}】${item.addressText}(自取)`
          } else {
            item.value = `【${item.merchantName}】${item.addressText}`
            if (item.otherInfo && item.otherInfo !== '') {
              item.value += `- ${item.otherInfo}`
            }
            if (item.companyName && item.companyName !== '') {
              item.value += `【${item.companyName}】`
            }
            item.value += `(距离: ${item.distance}千米)`
          }
          return item;
        });
        const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 1000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().includes(queryString.toLowerCase()));
        };
      },
      handleGetAddressList() {
        const memberIds = this.memberSelectionList.map(item => item.id)
        getListByMemberIds(memberIds.join(',')).then(res => {
          this.addressList = res.data.data;

          if (this.form.addressId && this.form.addressId !== '') {
            this.addressList.forEach(item => {
              if (item.id.toString() === this.form.addressId.toString()) {
                let addressName = ''
                if (item.isTakeSelf === 1) {
                  addressName = `【${item.merchantName}】${item.addressText}(自取)`
                } else {
                  addressName = `【${item.merchantName}】${item.addressText}`
                  if (item.otherInfo && item.otherInfo !== '') {
                    addressName += `- ${item.otherInfo}`
                  }
                  if (item.companyName && item.companyName !== '') {
                    addressName += `【${item.companyName}】`
                  }
                  addressName += `(距离: ${item.distance}千米)`
                }
                this.addressName = addressName;
              }
            })
          }
        })
      },
      handleRemove(index) {
        this.memberSelectionList.splice(index, 1)
        this.handleGetAddressList()
      },
      handleAddMemberClose() {
        this.addMemberVisible = false
      },
      handleAddMember() {
        this.addMemberVisible = true
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleSync() {
        this.$confirm("确定同步拼团地址数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return sync();
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          this.memberOnLoad(this.memberPage)
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            this.memberSelectionList = this.form.memberList
            this.masterMember = this.form.masterMember

            this.handleGetAddressList()
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      memberSearchReset() {
        this.onLoad(this.memberPage);
      },
      memberSearchChange(params, done) {
        this.memberPage.currentPage = 1;
        this.memberOnLoad(this.memberPage, params);
        done();
      },
      memberCurrentChange(currentPage){
        this.memberPage.currentPage = currentPage;
      },
      memberSizeChange(pageSize){
        this.memberPage.pageSize = pageSize;
      },
      searchNameChange(val) {
        this.memberOnLoad(this.memberPage, !val || val === '' ? {} : {name: val} )
      },
      memberOnLoad(page, params = {}) {
        this.loading = true;
        getMemberList(page.currentPage, page.pageSize, params).then(res => {
          const data = res.data.data;
          this.memberPage.total = data.total;
          this.memberData = data.records;
          this.loading = false;
          this.$refs.memberCrud.toggleSelection();
        });
      }
    }
  };
</script>

<style>
</style>
